package soria.cabinet.gui.components.assistance;

import soria.cabinet.security.Device;
import soria.cabinet.utils.SFont;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class KeyPosition {
    //Panel
    public static JPanel panel = new JPanel();
    //PublicKey TextArea
    private static final JTextArea RSA_AREA = new JTextArea();
    //SecretKey TextArea
    private static final JTextArea AES_AREA = new JTextArea();
    //公钥刷新按钮
    private static final JButton flushBtn =  new JButton("刷新");
    //获取密钥按钮
    private static final JButton getSecretKeyBtn = new JButton("获取密钥");


    static {
        panel.setLayout(null);
        panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLoweredBevelBorder(), "密钥", 2, 2, SFont.TITLE));
        panel.setBounds(410, 7, 410, 508);
        initial();
    }

    private static void initial(){
        RSA_AREA.setBounds(10, 25, 390, 200);
        RSA_AREA.setBorder(BorderFactory.createTitledBorder(null,"公钥",0,0,SFont.DEFAULT_CN));
        RSA_AREA.setFont(SFont.DEFAULT_EN);
        RSA_AREA.setText(Device.getPublicKey());
        RSA_AREA.setLineWrap(true);
        panel.add(RSA_AREA);

        AES_AREA.setBounds(10,300,390,200);
        AES_AREA.setBorder(BorderFactory.createTitledBorder(null,"解密所用密钥",0,0,SFont.DEFAULT_CN));
        AES_AREA.setFont(SFont.DEFAULT_EN);
        AES_AREA.setLineWrap(true);
        AES_AREA.setEditable(false);
        panel.add(AES_AREA);

        flushBtn.setBounds(30, 247, 130, 35);
        flushBtn.setFont(SFont.TEXT);
        flushBtn.addActionListener(new FlushListener());
        panel.add(flushBtn);

        getSecretKeyBtn.setBounds(250, 247, 130, 35);
        getSecretKeyBtn.setFont(SFont.TEXT);
        getSecretKeyBtn.addActionListener(new SecretKeyListener());
        panel.add(getSecretKeyBtn);
    }

    //事件监听器：点击刷新按钮即可重新获得自己的公钥
    private static class FlushListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            RSA_AREA.setText(Device.getPublicKey());
        }
    }

    //事件监听器：点击获取密钥按钮可根据JTextArea中的公钥来获取密钥
    private static class SecretKeyListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            String publicKey = RSA_AREA.getText();
            String secretKey = Device.getSecretKey(publicKey);
            AES_AREA.setText(secretKey);
        }
    }
}
